package com.weiz.repository;

import com.weiz.domain.SysPermission;
import com.weiz.domain.SysRole;
import com.weiz.domain.SysRolePermission;
import com.weiz.domain.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface SysUserRepository extends JpaRepository<SysUser, Long> {

    /**
     * 通过username查找 user
     * username是唯一的前提
     *
     * @param username
     * @return SysUser
     */
    @Query(value="select id,password,username from sys_user WHERE username=?1",nativeQuery = true)
    SysUser findUserByUsername(String username);

    /**
     * 通过用户名 查找·
     * @param username
     * @return List<SysRole>
     */
    @Query(value="select new com.weiz.domain.SysRole(sr.id,sr.name) \n" +
            "        from SysUser as su\n" +
            "        join su.roles as sr\n" +
            "        where su.username = ?1")
    List<SysRole> findRolesByUsername(String username);

    /**
     * 通过用户名 查找权限
     * @param username
     * @return List<SysPermission>
     */
    @Query(value=" select new com.weiz.domain.SysPermission(sp.id,sp.pid,sp.name,sp.url)\n" +
            "        from SysUser su\n" +
            "        join su.roles as sr\n" +
            "        join sr.permissions  as sp\n" +
            "        where su.username = ?1")
    List<SysPermission> findPermissionsByUsername(String username);

    @Query(value="select new com.weiz.domain.SysRolePermission(sr.id,sr.name,sp.id,sp.url,sp.name) \n" +
            "        from SysRole as sr\n"+
            "        join sr.permissions as sp")
    List<SysRolePermission> findAllRolePermissoin();

}
